# -*- coding: utf-8 -*-
# @Author : yanhaopeng
# @Date   : 2020/01/17
# @File   : EC04_ExtGuarBalToCapitalPro.py
# @E-mail : yanhaopeng@bbdservice.com

'''eof
name:对外担保余额(总)比注册资金
code:EC04_ExtGuarBalToCapitalPro_2D
tableName:
columnName:
groups:企业征信模块
dependencies:EC_DSJ_2D,IC_DSJ_2D,EG_DSJ
type:常用指标
dataSourceType:在线指标 description:这是获取 EC04 字段的数据脚本
eof'''

'''
1.Factor1=个人征信 [相关还款责任汇总信息段](PC02K)-[相关还款责任汇总信息](PC02KH)·还款责任类型(PC02KD02)∈(1(担保责任),)的余额(PC02KJ02)加总（单位：元）

2.Factor2=企业征信的担保交易相关还款责任汇总信息(EB05B)-担保交易相关还款责任汇总信息(EB05BH)·责任类型(EB05BD01)为2(保证人/反担保人 ) 的余额(EB05BJ02)（单位：元）

3.Factor3=企业征信的借贷交易相关还款责任汇总信息段(EB05A)-借贷交易相关还款责任汇总信息(EB05AH)·责任类型(EB05AD01)为2(保证人/反担保人 )的其他借贷交易账户余额(EB05AJ04)

4.将factor1、factor2、factor3之和转换为万元：Factor4 = (Factor1 + Factor2 + Factor3)/10000

5.Factor5 = 从工商数据中【企业照面信息】表中提取“注册资金（单位：万元）

6.Factor=Factor4/Factor5
'''

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None:
            return [{}]
        elif table == "":
            return ""
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)

    if occurTimes == 1:
        if table == "":
            return ""
        if table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        elif len(table) == 0:
            return [{}]
        else:
            return data.get(tableName)

def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def ECGuarantee():
    data = EC_DSJ_2D['data']
    ##企业征信的担保交易相关还款责任汇总信息
    # 相关还款责任汇总信息   [1..1]
    EBE=getTable(data,"EBE",1)
    if EBE is None:
        return  None
    elif EBE==[{}] or EBE == "":
        return 0
    else:
        # 相关还款责任汇总   [0..1]
        EB05=getTable(EBE[0],"EB05",0)
        if EB05 is None:
            return None
        elif EB05 == [{}] or EB05 == "":
            return 0
        else:
            factor1 = []
            factor2 = []
            # 借贷交易相关还款责任汇总信息段   [0..1]
            EB05A = getTable(EB05[0], "EB05A", 0)
            # 担保交易相关还款责任汇总信息段   [0..1]
            EB05B = getTable(EB05[0], "EB05B", 0)
            if EB05A is None or EB05A == "":
                factor1 = None
            elif EB05A == [{}]:
                factor1 = 0
            else:
                # 借贷交易相关还款责任汇总信息   [0..4]
                EB05AH = getTable(EB05A[0], "EB05AH", 0)
                if EB05AH is None or EB05AH == "":
                    factor1 = None
                elif EB05AH == [{}]:
                    factor1 = 0
                else:
                    for i in EB05AH:
                        try:
                            #责任类型(EB05AD01)为2(保证人\反担保人)的其他借贷交易账户余额(EB05AJ04)
                            EB05AD01 = i.get("EB05AD01")
                            EB05AJ04 = i.get("EB05AJ04")
                            if EB05AD01 in null_type_list or EB05AJ04 in null_type_list:
                                factor1.append(None)
                            elif EB05AD01 == '2' and isfloat(EB05AJ04):
                                factor1.append(float(EB05AJ04))
                            else:
                                factor1.append(0)
                        except:
                            factor1.append(None)
                            continue
                    factor1 = filter(lambda x: x is not None, factor1)
                    if len(factor1) == 0:
                        factor1 = None
                    else:
                        factor1 = sum(factor1)

            if EB05B is None or EB05B == "":
                factor2 = None
            elif EB05B == [{}]:
                factor2 = 0
            else:
                # 担保交易相关还款责任汇总信息   [0..4]
                EB05BH = getTable(EB05B[0], "EB05BH", 0)
                if EB05BH is None or EB05BH == "":
                    factor2 = None
                elif EB05BH == [{}]:
                    factor2 = 0
                else:
                    for i in EB05BH:
                        try:
                            # 责任类型(EB05BD01)为2(保证人\反担保人)的余额(EB05BJ02)
                            EB05BD01 = i.get("EB05BD01")
                            EB05BJ02 = i.get("EB05BJ02")
                            if EB05BD01 in null_type_list or EB05BJ02 in null_type_list:
                                factor2.append(None)
                            elif EB05BD01 == '2' and isfloat(EB05BJ02):
                                factor2.append(float(EB05BJ02))
                            else:
                                factor2.append(0)
                        except:
                            factor2.append(None)
                            continue
                    factor2 = filter(lambda x: x is not None, factor2)
                    if len(factor2) == 0:
                        factor2 = None
                    else:
                        factor2 = sum(factor2)


    if factor1 is None and factor2 is None:
        return None
    elif factor1 is None and factor2 is not None:
        return factor2
    elif factor1 is not None and factor2 is None:
        return factor1
    else:
        return factor1+factor2

def ICGuarantee():
    data = IC_DSJ_2D['data']
    # 信贷交易信息概要   [1..1]
    PCO = getTable(data, "PCO", 1)
    if PCO is None:
        return None
    elif PCO == [{}] or PCO == "":
        return 0
    else:
        # 信贷交易信息概要信息单元   [0..1]
        PC02 = getTable(PCO[0], "PC02", 0)
        if PC02 is None:
            return None
        elif PC02 == [{}] or PC02 == "":
            return 0
        else:
            # 相关还款责任汇总信息段   [0..1]
            PC02K = getTable(PC02[0], "PC02K", 0)
            if PC02K is None or PC02K == "":
                return None
            elif PC02K == [{}]:
                return 0
            else:
                # 相关还款责任汇总信息   [1..4]
                PC02KH = getTable(PC02K[0], "PC02KH", 1)
                if PC02KH is None or PC02KH == "":
                    return None
                elif PC02KH == [{}]:
                    return 0
                factor=[]
                for i in PC02KH:
                    try:
                        # 还款责任类型(PC02KD02)∈(1(担保责任))的余额(PC02KJ02)加总
                        PC02KD02 = i.get('PC02KD02')
                        PC02KJ02 = i.get('PC02KJ02')
                        if PC02KD02 in null_type_list or PC02KJ02 in null_type_list:
                            factor.append(None)
                        elif PC02KD02 == "1" and isfloat(PC02KJ02):
                            factor.append(float(PC02KJ02))
                        else:
                            factor.append(0)
                    except:
                        factor.append(None)
                        continue

                factorNotNone = filter(lambda x: x is not None, factor)
                if len(factorNotNone) == 0:
                    return None
                else:
                    return sum(factorNotNone)


def getTableEG(table_Name):
    try:
        null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
        data = EG_DSJ['data']['R1103V3'][0].get(table_Name)
        if data in null_type_list:
            return None
        else:
            if isinstance(data, list) and len(data) >= 1:
                return data
            else:
                return [{}]
    except:
        return None

#注册资本
def EGCapital():
    try:
        null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
        basic = getTableEG('basicList')
        if basic is None or basic == [{}]:
            return None
        else:
            if basic[0].get('regCap') not in null_type_list and isfloat(basic[0].get('regCap')):
                regCap = float(basic[0].get('regCap'))
                return regCap
            else:
                return None
    except:
        return None

def EC04_ExtGuarBalToCapitalPro():
    try:
        IC_guarantee = ICGuarantee()
        EC_guarantee = ECGuarantee()
        EG_capital = EGCapital()
        if IC_guarantee == 0 and EC_guarantee == 0 and EG_capital == 0:
            return 0
        elif EG_capital is None or EG_capital == 0:
            return u'缺失值'
        else:
            if IC_guarantee is None and EC_guarantee is None:
                return u'缺失值'
            else:
                if IC_guarantee is None:
                    IC_guarantee = 0.0
                else:
                    IC_guarantee = float(IC_guarantee) / 10000.0

                if EC_guarantee is None:
                    EC_guarantee = 0.0
                else:
                    EC_guarantee = float(EC_guarantee) / 10000.0
                result = round((IC_guarantee + EC_guarantee) / float(EG_capital), 4)
                return result
    except:
        return u'缺失值'
# if __name__ == "__main__":
#     import json
#     with open(r'C:\Users\zdr\Desktop\samples\EC_DSJ_2D.json') as ff:
#         EC_DSJ_2D = json.loads(ff.read())
#     with open(r'C:\Users\zdr\Desktop\samples\IC_DSJ_2D.json') as ff:
#         IC_DSJ_2D = json.loads(ff.read())
#     with open(r'C:\Users\zdr\Desktop\samples\EG_DSJ.json') as ff:
#         EG_DSJ = json.loads(ff.read())
#     aa = EC04_ExtGuarBalToCapitalPro()
#     print(aa)
result = EC04_ExtGuarBalToCapitalPro()









